import React, { useState, useEffect } from 'react';
import { Table, Button, message, Space } from 'antd';
import { getBorrowList, updateBorrowStatus, permitUpdate } from '../../../services/api';

const BorrowApprovalList = () => {
  const [loading, setLoading] = useState(false);
  const [borrowList, setBorrowList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const handleApproval = async (record, approved) => {
    try {
      setLoading(true);
      console.log('审批记录:', record);
      console.log('borrowId类型:', typeof record.borrowId);
      console.log('borrowId值:', record.borrowId);
      
      // 确保borrowId是数字
      const borrowId = parseInt(record.borrowId, 10);
      const requestData = {
        borrowStatus: approved ? '借用中' : '已拒绝'
      };
      
      console.log('发送请求:', {
        url: `/borrows/${borrowId}?method=updateBorrowStatus`,
        method: 'PUT',
        data: requestData
      });
      
      // 更新借用状态
      const updateStatusResponse = await updateBorrowStatus(borrowId, requestData);
      console.log('收到响应:', updateStatusResponse);

      if (updateStatusResponse.code === 200) {
        if (approved) {
          // 如果同意借用，则更新资产数量
          const updateAssetResponse = await permitUpdate(record.assetId, {
            assetNum: record.borrowNum, // 借用数量
            assetStatus: 'lendout' // 操作类型：借出
          });

          if (updateAssetResponse.code !== 200) {
            message.error('更新资产数量失败');
            return;
          }
        }
        message.success(approved ? '已同意借用申请' : '已拒绝借用申请');
        fetchBorrowList(); // 刷新列表
      } else {
        message.error(updateStatusResponse.message || '操作失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '借用ID',
      dataIndex: 'borrowId',
      key: 'borrowId',
    },
    {
      title: '借用人',
      dataIndex: 'uName',
      key: 'uName',
    },
    {
      title: '所属部门',
      dataIndex: 'depName',
      key: 'depName',
    },
    {
      title: '资产名称',
      dataIndex: 'assetName', // 实体属性
      key: 'assetName',
    },
    {
      title: '借用状态',
      dataIndex: 'borrowStatus', // 实体属性
      key: 'borrowStatus',
    },
    {
      title: '借用数量',
      dataIndex: 'borrowNum',
      key: 'borrowNum',
    },
    {
      title: '当前可用数量',
      dataIndex: 'currentAssetNum',
      key: 'currentAssetNum',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => ( // render和dataSource绑定，dataSource又为获取的字典列表，每个元素为一个字典包含申请信息键值对
        record.borrowStatus === '待审批' ? (
          <Space size="small">
            <Button 
              type="primary" 
              onClick={() => handleApproval(record, true)}
              disabled={record.borrowNum > record.currentAssetNum}
            >
              同意
            </Button>
            <Button danger onClick={() => handleApproval(record, false)}>
              拒绝
            </Button>
          </Space>
        ) : null
      ),
    },
  ];

  const fetchBorrowList = async () => {
    try {
      setLoading(true);
      const response = await getBorrowList();
      if (response.code === 200 && Array.isArray(response.data)) {
        // 只显示待审批的记录
        const filteredList = response.data.filter(item => item.borrowStatus === '待审批');
        setBorrowList(filteredList);
        setPagination(prev => ({
          ...prev,
          total: filteredList.length
        }));
      } else {
        message.error(response.message || '获取借用记录失败');
      }
    } catch (error) {
      console.error('获取借用记录失败:', error);
      message.error('获取借用记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchBorrowList();
  }, []);

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  return (
    <div style={{ padding: '24px' }}>
      <h2>借用审批列表</h2>
      <Table
        columns={columns}
        dataSource={borrowList}
        rowKey="borrowId"
        pagination={pagination}
        onChange={handleTableChange}
        loading={loading}
      />
    </div>
  );
};

export default BorrowApprovalList; 